//
//  MuytAppDelegate.m
//  Muyt
//
//  Created by murnork on 7/12/10.
//  Copyright 2010 cocomputing.com. All rights reserved.
//

#import "MuytAppDelegate.h"
#import "ASIHTTPRequest.h"
#import "MuytDefinition.h"

@implementation MuytAppDelegate

@synthesize window;
@synthesize urlField;
@synthesize startButton;
@synthesize downloadProgressIndicator;
@synthesize filenameLabel;
@synthesize downloadCount;
@synthesize imagePageContent;
@synthesize originalURL;
@synthesize downloadCountDict;

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
	[self.downloadProgressIndicator setHidden:YES];
	[self.filenameLabel setHidden:YES];
	[self.window setFrame:CGRectMake(550, 525, 572, 62 + [self titleBarHeight]) display:YES];
	
	[self.urlField setStringValue:DEFAULT_URL]; 
	
	NSMutableDictionary *dict = [NSMutableDictionary dictionary];
	[[NSUserDefaults standardUserDefaults] registerDefaults:dict];
	
	self.downloadCountDict = [NSMutableDictionary dictionary];

	if ([[NSUserDefaults standardUserDefaults] objectForKey:@"D-DownloadCount"] != nil) {
		[self.downloadCountDict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"D-DownloadCount"] forKey:@"D-DownloadCount"];
	}
	else {
		[self.downloadCountDict setObject:@"0" forKey:@"D-DownloadCount"];
	}
	
	if ([[NSUserDefaults standardUserDefaults] objectForKey:@"K-DownloadCount"] != nil) {
		[self.downloadCountDict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"K-DownloadCount"] forKey:@"K-DownloadCount"];
	}
	else {
		[self.downloadCountDict setObject:@"0" forKey:@"K-DownloadCount"];
	}
	
	if ([[NSUserDefaults standardUserDefaults] objectForKey:@"M-DownloadCount"] != nil) {
		[self.downloadCountDict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:@"M-DownloadCount"] forKey:@"M-DownloadCount"];
	}
	else {
		[self.downloadCountDict setObject:@"0" forKey:@"M-DownloadCount"];
	}
}

- (BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
	return YES;
}

- (void)applicationWillTerminate:(NSNotification *)aNotification
{
	if ([self.originalURL rangeOfString:@"danbooru"].length != 0) {
		[[NSUserDefaults standardUserDefaults] setObject:self.downloadCount forKey:@"D-DownloadCount"];
	}
	else if ([self.originalURL rangeOfString:@"konachan"].length != 0) {
		[[NSUserDefaults standardUserDefaults] setObject:self.downloadCount forKey:@"K-DownloadCount"];
	}
	else if ([self.originalURL rangeOfString:@"imouto"].length != 0) {
		[[NSUserDefaults standardUserDefaults] setObject:self.downloadCount forKey:@"M-DownloadCount"];
	}
}

- (float) titleBarHeight
{
    NSRect frame = NSMakeRect (0, 0, 100, 100);
    NSRect contentRect;
    contentRect = [NSWindow contentRectForFrameRect: frame styleMask: NSTitledWindowMask];
    return (frame.size.height - contentRect.size.height);
}

- (BOOL)haveDuplicateImageWithFileName:(NSString *)imageFileName inPath:(NSString *)imageMainPath
{
	NSFileManager * fileManager = [NSFileManager defaultManager];
	//check current directory
	if ([fileManager fileExistsAtPath:[[imageMainPath stringByExpandingTildeInPath] stringByAppendingPathComponent:imageFileName]]) {
		return YES;
	}
	//check sub directory
	NSDirectoryEnumerator * subPaths;
	subPaths = [fileManager enumeratorAtPath:[imageMainPath stringByExpandingTildeInPath]];
	NSString * subDirectoryInPath;
	while (subDirectoryInPath = [subPaths nextObject]) {
		if ([fileManager fileExistsAtPath:[[[imageMainPath stringByExpandingTildeInPath] stringByAppendingPathComponent:subDirectoryInPath] stringByAppendingPathComponent:imageFileName]]) {
			return YES;
		}
	}
	return NO;
}

- (NSString *)downloadDestinationWithFileName:(NSString *)filename inPath:(NSString *)mainPath
{
	NSString *savePath = [NSString stringWithString:[mainPath stringByExpandingTildeInPath]];
	
	if ([self.originalURL rangeOfString:@"danbooru"].length != 0) {
		savePath = [savePath stringByAppendingPathComponent:@"Danbooru"];
	}
	else if ([self.originalURL rangeOfString:@"konachan"].length != 0) {
		savePath = [savePath stringByAppendingPathComponent:@"Konachan"];
	}
	else if ([self.originalURL rangeOfString:@"imouto"].length != 0) {
		savePath = [savePath stringByAppendingPathComponent:@"Moe.Imouto"];
	}
		
	NSFileManager * fileManager = [NSFileManager defaultManager];
	NSArray * mainDirectoryContent;
	NSArray * subDirectoryContent;
	int subDirectoryCount = 0;
	int fileCount = 0;
	
	if ([fileManager fileExistsAtPath:savePath]) {
		mainDirectoryContent = [fileManager contentsOfDirectoryAtPath:savePath error:NULL];
		
		if ([mainDirectoryContent containsObject:@".DS_Store"]) {
			subDirectoryCount = [mainDirectoryContent count] - 1;
		}
		else {
			subDirectoryCount = [mainDirectoryContent count];
		}
		
		if (subDirectoryCount != 0) {
			NSString *subDir = [savePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%04d", subDirectoryCount]];
			
			subDirectoryContent = [fileManager contentsOfDirectoryAtPath:subDir error:NULL];
			
			if ([subDirectoryContent containsObject:@".DS_Store"]) {
				fileCount = [subDirectoryContent count] - 1;
			}
			else {
				fileCount = [subDirectoryContent count];
			}
			
			if (fileCount >= DIRECTORY_CAPACITY) {
				savePath = [savePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%04d", subDirectoryCount + 1]];
			}
			else {
				savePath = [savePath stringByAppendingPathComponent:[NSString stringWithFormat:@"%04d", subDirectoryCount]];
			}
		}
		else {
			savePath = [savePath stringByAppendingPathComponent:@"0001"];
		}
	}
	else {
		savePath = [savePath stringByAppendingPathComponent:@"0001"];
	}
	
	[fileManager createDirectoryAtPath:savePath withIntermediateDirectories:YES attributes:nil error:NULL];
	
	return [savePath stringByAppendingPathComponent:filename];
}

- (IBAction)startDownloadImage:(id)sender
{
	self.originalURL = [self.urlField stringValue];

	[self.downloadProgressIndicator setHidden:NO];
	[self.downloadProgressIndicator setIndeterminate:YES];
	[self.downloadProgressIndicator startAnimation:nil];
	[self.filenameLabel setHidden:NO];
	
	[self.window setFrame:CGRectMake([self.window frame].origin.x, [self.window frame].origin.y - (120 - 62), [self.window frame].size.width, 120 + [self titleBarHeight]) display:YES animate:YES];
	
	if ([self.originalURL rangeOfString:@"danbooru"].length != 0) {
		if ([self.downloadCountDict objectForKey:@"D-DownloadCount"] != nil) {
			self.downloadCount = [self.downloadCountDict objectForKey:@"D-DownloadCount"];
		}
		else {
			self.downloadCount = @"0";
		}
	}
	else if ([self.originalURL rangeOfString:@"konachan"].length != 0) {
		if ([self.downloadCountDict objectForKey:@"K-DownloadCount"] != nil) {
			self.downloadCount = [self.downloadCountDict objectForKey:@"K-DownloadCount"];
		}
		else {
			self.downloadCount = @"0";
		}
	}
	else if ([self.originalURL rangeOfString:@"imouto"].length != 0) {
		if ([self.downloadCountDict objectForKey:@"M-DownloadCount"] != nil) {
			self.downloadCount = [self.downloadCountDict objectForKey:@"M-DownloadCount"];
		}
		else {
			self.downloadCount = @"0";
		}
	}
	
	[self.urlField setEnabled:NO];
	
	[sender setEnabled:NO];

	[self downloadImage];
	
	return;
}

- (void)downloadImage
{
	[self.downloadProgressIndicator setIndeterminate:YES];
	[self.downloadProgressIndicator startAnimation:nil];
	
	if ([self.originalURL rangeOfString:@"danbooru"].length != 0) {
		[[NSUserDefaults standardUserDefaults] setObject:self.downloadCount forKey:@"D-DownloadCount"];
	}
	else if ([self.originalURL rangeOfString:@"konachan"].length != 0) {
		[[NSUserDefaults standardUserDefaults] setObject:self.downloadCount forKey:@"K-DownloadCount"];
	}
	else if ([self.originalURL rangeOfString:@"imouto"].length != 0) {
		[[NSUserDefaults standardUserDefaults] setObject:self.downloadCount forKey:@"M-DownloadCount"];
	}
	
	NSString *urlString;
	
	if ([[self.urlField stringValue] hasPrefix:@"http://"]) {
		if ([[self.urlField stringValue] hasSuffix:@"/"]) {
			urlString = [[self.urlField stringValue] stringByAppendingFormat:@"%@", self.downloadCount];
		}
		else {
			urlString = [[self.urlField stringValue] stringByAppendingFormat:@"/%@", self.downloadCount];
		}
	}
	else {
		if ([[self.urlField stringValue] hasSuffix:@"/"]) {
			urlString = [@"http://" stringByAppendingFormat:@"%@", [[self.urlField stringValue] stringByAppendingFormat:@"%@", self.downloadCount]];
		}
		else {
			urlString = [@"http://" stringByAppendingFormat:@"%@", [[self.urlField stringValue] stringByAppendingFormat:@"/%@", self.downloadCount]];
		}
	}
	
	NSURL *url = [NSURL URLWithString:urlString];
	
	getImagePageRequest = [ASIHTTPRequest requestWithURL:url];
	[getImagePageRequest setDelegate:self];
	[getImagePageRequest setDidFailSelector:@selector(getImagePageContentFailed:)];
	[getImagePageRequest setDidFinishSelector:@selector(getImagePageContentFinished:)];
	[getImagePageRequest startAsynchronous];
}

- (void)getImagePageContentFinished:(ASIHTTPRequest *)request
{
	retryCount = 0;
	
	self.imagePageContent = [request responseString];

	NSString *imageLocationString = [self imageURLByParsingImagePageContent];
	[self.window setTitle:[@"Muyt" stringByAppendingFormat:@" - %@", self.downloadCount]];
	
	[self.filenameLabel setStringValue: (imageLocationString != nil) ? [imageLocationString lastPathComponent] : @""];
	
	if ([self haveDuplicateImageWithFileName:[[imageLocationString stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding] lastPathComponent] inPath:Main_Image_Save_Path]) {
		[self performSelector:@selector(getImageFileFinished:)];
		return;
	}

	NSURL *imageURL = [NSURL URLWithString:[[self imageURLByParsingImagePageContent] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
	
	[self getImageFileFromURL:imageURL];
}

- (void)getImagePageContentFailed:(ASIHTTPRequest *)request
{
	if (retryCount > Max_Retry_Count) {
		[self performSelector:@selector(getImageFileFinished:)];
		return;
	}
	
	[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"Domain = %@; Code = %d; Description = %@", [[request error] domain], [[request error] code], [[request error] localizedDescription]] forKey:[@"Error: " stringByAppendingFormat:@"%@", request.originalURL]];
	[self performSelector:@selector(downloadImage) withObject:nil afterDelay:Retry_Interval];
	retryCount++;
}

- (NSString *)imageURLByParsingImagePageContent
{
	NSArray *contentArray = [self.imagePageContent componentsSeparatedByString:@"\n"];
	
	for(NSString *line in contentArray) {		
		if ([self.originalURL rangeOfString:@"danbooru"].length != 0) {
			if ([line rangeOfString:@"id=\"highres\""].length != 0 && [line rangeOfString:@"/data/"].length != 0) {
				return [[[[[line componentsSeparatedByString:@"href=\""] objectAtIndex:1] componentsSeparatedByString:@"\""] objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
			}
		}
		else {
			if ([line rangeOfString:@"original-file-"].length != 0) {
				if ([line rangeOfString:@"id=\"png\""].length != 0) {
					return [[[[[line componentsSeparatedByString:@"href=\""] objectAtIndex:1] componentsSeparatedByString:@"\""] objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
				}
				else if ([line rangeOfString:@"id=\"highres\""].length != 0 && [line rangeOfString:@"/image/"].length != 0) {
					return [[[[[line componentsSeparatedByString:@"href=\""] objectAtIndex:1] componentsSeparatedByString:@"\""] objectAtIndex:0] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
				}
			}
		}
	}
	
	return nil;
}

- (void)getImageFileFromURL:(NSURL *)imageURL
{
	[self.downloadProgressIndicator setIndeterminate:NO];
	
	NSString *filename = [[imageURL lastPathComponent] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
		
	getImageFileRequest = [ASIHTTPRequest requestWithURL:imageURL];
	[getImageFileRequest setDelegate:self];
	[getImageFileRequest setDidFailSelector:@selector(getImageFileFailed:)];
	[getImageFileRequest setDidFinishSelector:@selector(getImageFileFinished:)];
	[getImageFileRequest setDownloadProgressDelegate:self.downloadProgressIndicator];
	[getImageFileRequest setDownloadDestinationPath:[self downloadDestinationWithFileName:filename inPath:Main_Image_Save_Path]];
	[getImageFileRequest startAsynchronous];
}

- (void)getImageFileFinished:(ASIHTTPRequest *)request
{
	retryCount = 0;
	
	self.downloadCount = [NSString stringWithFormat:@"%d", [self.downloadCount intValue] + 1];
	
	[self performSelector:@selector(downloadImage) withObject:nil afterDelay:Download_Interval];
}

- (void)getImageFileFailed:(ASIHTTPRequest *)request
{
	if (retryCount > Max_Retry_Count) {
		[self performSelector:@selector(getImageFileFinished:)];
		return;
	}
	
	[[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"Domain = %@; Code = %d; Description = %@", [[request error] domain], [[request error] code], [[request error] localizedDescription]] forKey:[@"Error: " stringByAppendingFormat:@"%@", request.originalURL]];
	[self performSelector:@selector(downloadImage) withObject:nil afterDelay:Retry_Interval];
	retryCount++;
}

@end
